package com.example.ims.fame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.springframework.context.ApplicationContext;

import com.example.ims.service.CommodityService;

public class TransferFame extends JDialog {
    private JTextField locationTextField;
    private CommodityService commodityService;
    private Long commodityId;
    private ApplicationContext context;

    public TransferFame(Frame owner, String title, boolean modal, ApplicationContext context, Long commodityId) {
        super(owner, title, modal);
        this.context = context;
        this.commodityId = commodityId;
        commodityService = context.getBean(CommodityService.class);
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridLayout(3, 2));

        JLabel locationLabel = new JLabel("新位置:");
        locationTextField = new JTextField();

        JButton confirmButton = new JButton("确认");
        JButton cancelButton = new JButton("取消");

        confirmButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                String newLocation = locationTextField.getText();
                try {
                    // 调用CommodityService的方法更新商品位置信息
                    commodityService.updateLocation(commodityId, newLocation);
                    JOptionPane.showMessageDialog(TransferFame.this, "商品调拨成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(TransferFame.this, "商品调拨失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        add(locationLabel);
        add(locationTextField);
        add(confirmButton);
        add(cancelButton);

        setSize(300, 150);
        setLocationRelativeTo(getOwner());
    }
}